package hu.gar.core.service.impl;

import hu.gar.core.dao.UserDao;
import hu.gar.core.dao.UserToRoleDao;
import hu.gar.core.entity.Role;
import hu.gar.core.entity.User;
import hu.gar.core.service.CustomUserDetailsService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("customUserDetailsService")
@Transactional(propagation = Propagation.REQUIRED)
public class CustomUserDetailsServiceImpl implements CustomUserDetailsService {

	private static final long serialVersionUID = 3978946326490349408L;

	@Autowired
	UserDao userDao;

	@Autowired
	UserToRoleDao userToRoleDao;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = userDao.findByName(username);

		if (user == null) {
			throw new UsernameNotFoundException(username);
		}
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		List<Role> roles = userToRoleDao.findByUserId(user.getId());
		for (Role role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getRole()));

		}
		return new org.springframework.security.core.userdetails.User(
				user.getUsername(), user.getPassword(), authorities);
	}
}
